package com.idea.zd.sys.train.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class ThreadPoolTest {

    /**
     * 线程池初始化方法
     *
     * corePoolSize 核心线程池大小----10
     * maximumPoolSize 最大线程池大小----30
     * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----30+单位TimeUnit
     * TimeUnit keepAliveTime时间单位----TimeUnit.MINUTES
     * workQueue 阻塞队列----new ArrayBlockingQueue<Runnable>(10)====10容量的阻塞队列
     * threadFactory 新建线程工厂----new CustomThreadFactory()====定制的线程工厂
     * rejectedExecutionHandler 当提交任务数超过maxmumPoolSize+workQueue之和时,
     * 							即当提交第41个任务时(前面线程都没有执行完,此测试方法中用sleep(100)),
     * 						          任务会交给RejectedExecutionHandler来处理
     */
    public static void main(String [] args){
        //ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("%d").build();
        System.out.println("12321321");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 5, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(2));
        //executor.allowCoreThreadTimeOut(true);
        System.out.println(executor.getPoolSize());

        for(int i=1;i<=7;i++){
            MyTask myTask = new MyTask(i);
            //executor.execute(myTask);
            executor.submit(myTask);
            System.out.println("线程池中线程数目："+executor.getPoolSize()+"，队列中等待执行的任务数目："+
                    executor.getQueue().size()+"，已执行玩别的任务数目："+executor.getCompletedTaskCount());
        }

        executor.shutdown();


    }
}

class MyTask implements Runnable {
    private int taskNum;

    public MyTask(int num) {
        this.taskNum = num;
    }

    @Override
    public void run() {
        System.out.println("正在执行task "+taskNum+"\n:线程名为:"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(1/0);
        System.out.println("task "+taskNum+"执行完毕" + Thread.currentThread().getName());
    }
}
